package com.tsj.spzx.service.Impl;

import cn.hutool.core.date.DateUtil;
import com.tsj.spzx.exception.TsjException;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import com.tsj.spzx.properties.FileUploadProperties;
import com.tsj.spzx.service.FileUpService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class FileUpServiceImpl implements FileUpService {

    @Autowired
    private FileUploadProperties fileUploadProperties;

    @Override
    public String fileUpload(MultipartFile file) {

        try {
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(fileUploadProperties.getHostAndPort())
                    .credentials(fileUploadProperties.getMinioUsername(), fileUploadProperties.getMinioPassword())
                    .build();

            // 判断桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(fileUploadProperties.getBucketName()).build());
            if (!found) {       // 如果不存在，那么此时就创建一个新的桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(fileUploadProperties.getBucketName()).build());
            } else {  // 如果存在打印信息
                System.out.println("Bucket 'spzx-bucket' already exists.");
            }

            // 文件上传
            // 根据日期创建文件夹 并修改文件名字
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String filename = dateDir + "/"
                              + UUID.randomUUID().toString().replaceAll("-", "")
                              + file.getOriginalFilename();

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(fileUploadProperties.getBucketName())
                            .object(filename)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            // 获取文件在minio中的路径，因为我们设置的bucket为public，所以可以直接用该方式访问
            return fileUploadProperties.getHostAndPort() + "/" + fileUploadProperties.getBucketName() + "/" + filename;
        } catch (Exception e) {
            throw new TsjException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
